using System;
using System.Collections.Generic;
using System.Text;
using System.Configuration;
using System.Web.Configuration;
using StructureMap;

namespace Impact.Infrastructure.Configuration
{
    /// <summary>
    /// provider for the configuration used in production runtime
    /// </summary>
    [Pluggable("RuntimeConfigProvider")]
    public class RuntimeConfigProvider : IConfigProvider
    {
        private ImpactSettings settings;

        #region IConfigProvider Members

        /// <summary>
        /// Gets or Sets the section of the config pertaining to the impact application
        /// </summary>
        public ImpactSettings Settings
        {
            get
            {
                if (settings == null)
                {
                    settings = (ImpactSettings)WebConfigurationManager.GetSection("impact");
                }
                return settings;
            }
            set
            {
                if (value != null)
                {
                    System.Configuration.Configuration config = WebConfigurationManager.OpenWebConfiguration("~/");
                    settings = (ImpactSettings)config.GetSection("impact");

                    settings.DefaultPage = value.DefaultPage;
                    settings.PageTitlePrefix = value.PageTitlePrefix;
                    settings.FooterText = value.FooterText;
                    settings.WebmasterEmail = value.WebmasterEmail;
                    settings.MenuStyle = value.MenuStyle;
                    settings.ArticleFolder = value.ArticleFolder;
                    settings.ArticleTemplate = value.ArticleTemplate;
                    settings.CategoryTemplate = value.CategoryTemplate;
                    settings.TagTemplate = value.TagTemplate;


                    try
                    {
                        config.Save(ConfigurationSaveMode.Modified);
                    }
                    catch (UnauthorizedAccessException ex)
                    {
                        throw new UnauthorizedAccessException("Cannot write web.config.  This can happen if ASP.NET is not configured with Write permissions on the web.config in the application folder.", ex);
                    }
                }

            }
        }

        #endregion
    }
}
